<template>
    <div class="layoutContainer form-custom-view-container" >
        <div v-if="!isFullShow" class="layoutContainer-head">
            <my-icon @click="downLoad" type="iconcloud-download" :title="i18n('list.downloadImg','下载图片')"></my-icon>
            <my-icon v-if="showShare" type="iconshare" @click="share" :title="i18n('list.share','分享')"></my-icon>
            <my-icon v-if="!layerid" @click="fullScreen" type="iconmodal-fullscreen" :title="i18n('list.fullScreen','全屏')"></my-icon>
        </div>
        <div class="Loading" v-if="Loading">
           <div style="margin: auto">
               <a-spin size="large" />
               <p style="color: #1890ff">{{i18n('list.loadingImg','拼命下载图片中...')}}</p>
           </div>
        </div>
        <div id="formCustomView">
            <grid-layout v-show="type=='drag'"
                         :layout="LayoutList"
                         :col-num="24"
                         :row-height="2"
                         :is-draggable="false"
                         :is-resizable="false"
                         :is-mirrored="false"
                         :vertical-compact="true"
                         :autoSize="true"
                         :margin="[10, 10]"
                         :use-css-transforms="true"
            >

                <grid-item class="gridItem" v-for="item in LayoutList"
                           :x="item.x"
                           :y="item.y"
                           :w="item.w"
                           :h="item.h"
                           :i="item.i"
                           :key="item.i">
                    <!--图标放大-->
                    <div v-if="!isFullShow && isShow.indexOf(item.defConf)<=-1 && item.config.fullBtn" class="gridItem-fullscreen"><my-icon @click="fullScreenChild(item)" type="iconmodal-fullscreen"></my-icon></div>
                    <FormCustomEditControl :item="item" :ref="item.id" :readonly="true"></FormCustomEditControl>
                </grid-item>
            </grid-layout>
            <custom-layout class="gridItem" style="height: 100%" v-show="type=='custom'" :key="layoutKey" :allModel="allModel">
                <div
                    v-for="item of lay"
                    :slot="item"
                    v-if="allModel.layoutModel[item]"
                    :layoutStyle="allModel[item].toolStyle"
                    style="height:100%"
                    :key="item"
                >
                    <template v-if="allModel[item].showTab =='no' && allModel[item].selectModel.config">
                        <component :ref="allModel[item].selectModel.config.alias"
                                   :is="allModel[item].selectModel.config.component"
                                   :config="allModel[item].selectModel.config"
                                   :key='new Date().getTime()'
                        >
                        </component>
                    </template>
                    <template v-if="allModel[item].showTab =='yes'">
                        <layout-tab :ref="item" :config="allModel[item].tabData"  :key='item'></layout-tab>
                    </template>
                </div>
            </custom-layout>
        </div>
    </div>

</template>

<script>
import FormCustomApi from "@/api/form/core/formCustom";
import customLayout from "../formCustomLayout/CustomLayout.vue";
import layoutTab from "../formCustomLayout/LayoutTab.vue";
import FormComponent from "./FormComponent";
import ListComponent from "./ListComponent";
import TreeComponent from "./TreeCompoment";
import html2canvas from "html2canvas";
import FormCustomEditControl from '@/views/modules/form/core/FormCustomEditControl';
import  FormCustomFull from "./FormCustomFull"
import {Util} from "@lowcode/jpaas-common-lib";
import {mapMutations, mapState} from "vuex";
import FormCustomShare from  "@/views/modules/form/core/formComponent/FormCustomShare.vue"


export default {
    name: "form-custom-view",
    props: {
        layout: {
            type: Array,
            default: () => []
        },
        alias: {
            type: String
        },
        params: {
            type: String
        },
        //这个是从DialogView打开时需要用到的。
        menuParams:{
            type:String
        },
        layerid: {
            type: String,
            default: ""
        },
        destroy: {
            type: Function
        },
    },
    computed: {
        ...mapState({
            navigation: state => state.appSetting.navigation,
            frontType: state => state.appSetting.frontType,
        })
    },
    components: {
        customLayout,
        layoutTab,
        FormCustomFull,
        FormCustomEditControl,
        FormComponent,
        ListComponent,
        TreeComponent
    },
    data() {
        return {
            dragShow:true,
            scrollWidth:0,
            keyShow:new Date().getTime(),
            isFormCustom:true,
            fromRoute: false,
            layoutKey: 'mainLayout',
            lay: ["header", "inheader", "left", "right", "center", "footer", "infooter"],
            allModel: {
                layoutModel: {
                    header: false,
                    inheader: false,
                    left: false,
                    right: false,
                    footer: false,
                    infooter: false,
                    center: false
                },
                header: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                inheader: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                left: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                right: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                center: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                footer: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
                infooter: {
                    selectModel: {
                        name: "",
                        config: {}
                    },
                    toolStyle: "",
                    showTab: 'no',
                    tabData: []
                },
            },
            type: 'drag',
            dataAlias:'',
            isFullShow :false,
            formCustom:{},
            showShare:true,
            //加密参数
            encryParams:{},
            isShow:['filter'],
            Loading:false,
            LayoutList:this.layout,
        }
    },
    mounted() {
        this.initParams();
        this.init();
        var that = this;
        window.onresize=()=>{
            that.checkFull()
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formComponent", key);
        },
        ...mapMutations('appSetting', ['setNavigation','setActiveKey']),
        //单独全屏
        fullScreenChild(item){
            //流程自建
            let data={item: item};
            if(item.defConf=="bpm"){
                let itemVue= this.$refs[item.id]
                let bpmVue=itemVue[0].$refs[item.config.alias].$refs.openBpm;
                if(bpmVue && bpmVue.instId){
                    data.instId=bpmVue.instId;
                }
            }
            var baseConf = {
                component: FormCustomFull,
                curVm: this,
                title: ' ',
                max: true,
                data: data
            }
            Util.open(baseConf, function (action, data) {
            })
        },
        //全屏
        fullScreen(){
            this.show = false;
            let el=document.querySelector("div.form-custom-view-container");
            el.requestFullscreen();
        },
        //判断是否大屏
        checkFull(){
            if(!this.dataAlias){
                this.isFullShow=true;
                return;
            }
            let isFull = window.fullScreen || document.webkitIsFullScreen;
            this.isFullShow=isFull
        },
        //下载图片
        downLoad(){
            //对指定容器进行截屏
            this.Loading = true;
            var that = this;
            setTimeout(function(){
                that.isHtml2canvas()
            },100)
        },
        isHtml2canvas(){
            var scrollHeight = document.getElementById('formCustomView').scrollHeight
            html2canvas(document.getElementById("formCustomView"), {
                backgroundColor: '#ececec', //画布背景色（如果未在DOM中指定）。设置null为透明
                allowTaint: true,
                useCORS: true,
                scale: 2, // 处理模糊问题
                dpi: 350, // 处理模糊问题
                height: scrollHeight,
                windowHeight: scrollHeight
            }).then((canvas) => {
                let canvasImg = canvas.toDataURL("image/png",1);
                //调用下载方法
                this.downLoadFile("simple", canvasImg);
            });
        },
        downLoadFile(fileName, canvasImg) {
            //创建一个a标签
            var a = document.createElement("a");
            //指定下载文件名称
            a.href = canvasImg;
            a.download = fileName;
            //模拟点击
            a.click();
            this.Loading = false
        },
        initParams(){
            if (!this.alias) {
                if(this.menuParams){
                    var json=JSON.parse(this.menuParams);
                    this.dataAlias=json.alias;
                }
                else {
                    if(this.$route.meta.params){
                        var json=JSON.parse(this.$route.meta.params);
                        this.dataAlias=json.alias;
                        this.$route.meta.query = this.$route.meta.params;
                    }else {
                        //为加密参数
                        if(this.$route.params.encryParams){
                            let decryStr = window.atob(this.$route.params.encryParams); // 解码
                            var paramStr=window.decodeURIComponent(decryStr);
                            if(paramStr){
                                this.encryParams=JSON.parse(paramStr);
                                this.dataAlias=this.encryParams.alias;
                                //分享的路径不允许再分享
                                this.showShare=false;
                            }
                        }else {
                            this.dataAlias=this.$route.params.alias;
                        }
                    }
                }
                //从路由打开
                this.fromRoute = true;
            }else {
                this.dataAlias=this.alias;
            }
            if (this.params) {
                let params_ = this.params;
                if (typeof params_ == 'string') {
                    params_ = JSON.parse(params_)
                }
                let metaParams = this.$route.meta.params ? JSON.parse(this.$route.meta.params) : {};
                this.$route.meta.params = JSON.stringify(Object.assign(metaParams, params_));
            }
        },
        init() {
            var self = this;
            if(!this.dataAlias){
                this.isFullShow=true;
                return;
            }
            FormCustomApi.getByAlias(this.dataAlias).then(res => {
                self.type = res.type;
                if (res.type == 'drag') {
                    self.LayoutList = JSON.parse(res.json);
                } else {
                    if(res){
                        self.allModel = JSON.parse(res.json);
                    }
                }
                self.formCustom=res;
                //页签打开
                let routeKey='customView';
                if(routeKey==this.$route.name){
                    let index = this.navigation[this.frontType].findIndex(obj=>{ return obj.key == routeKey});
                    if( index< 0 ){
                        this.navigation[this.frontType].push({
                            key: routeKey,
                            title: res.name,
                            collapsed: true,
                            path:self.$route.path,
                            params:self.$route.params,
                            query:self.$route.query
                        })
                    }
                    //配置tab选中key
                    this.setActiveKey(routeKey);
                }
            })
        },
        getCustomById(customId) {
            var self = this;
            FormCustomApi.get(customId).then(res => {
                var data=res.data;
                self.type = data.type;
                if (data.type == 'drag') {
                    self.LayoutList = JSON.parse(data.json);
                } else {
                    self.allModel = JSON.parse(data.json);
                }
            })
        },
        //分享
        share(){
            var baseConf = {
                component: FormCustomShare,
                curVm: this,
                title: this.i18n('list.sharePage','分享页面：')+this.formCustom.name||"",
                widthHeight: ['900px', '400px'],
                data: {
                    formCustom: this.formCustom,
                },
            }
            Util.open(baseConf, function (action, data) {
            })
        },
    },
    watch: {
        '$route': {
            handler: function (val) {
                if(val.meta.param){
                    var json=JSON.parse( val.meta.params);
                    this.dataAlias = json.alias;
                    val.meta.query = val.meta.params;
                    if(this.params){
                        val.meta.query=this.params;
                    }
                }else {
                    this.dataAlias=val.params.alias;
                }
                this.initParams();
                this.init();
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.Loading{
    position: fixed;
    width: 100%;
    height: 100%;
    display:flex;
    text-align: center;
    justify-items: center;
    align-items: center;
    background-color: rgba(0,0,0,.45);
    z-index: 99;
}
.gridItem{
    position: relative;
}
.gridItem:hover .gridItem-fullscreen{
    display: block;
}
.gridItem-fullscreen{
    position: absolute;
    top: 10px;
    left: 10px;
    font-size: 22px;
    cursor: pointer;
    display: none;
    z-index: 99;
    background: #1890ff;
    width: 30px;
    height: 30px;
    border-radius: 5px;
    color: white;
    text-align: center;
    line-height: 30px;
}
.layoutContainer-head{
    height: 35px;
    text-align: right;
    line-height: 35px;
    background-color: white;
    font-size: 22px;
}
.layoutContainer-head i{
    margin-right: 15px;
    cursor: pointer;
}
.layoutContainer-head i:hover{
    color: #0e62e8;
}
.layoutContainer {
    width: 100%;
    height: 100%;
    background: #f0f2f5;
    display: flex;
    flex-direction: column;
}
.layoutContainer >div:nth-child(2){
    flex: 1;
    overflow: auto
}
.ant-btn-primary {
    margin-right: 6px;
}

.btnSpan {
    border-radius: 10px;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 18px;
    background: #1890ff;
    display: inline-block;
    margin-right: 6px;
    cursor: pointer;
}

.btnSpan i {
    color: #fff;
    font-size: 10px;
    margin-top: 3px;
}

.gridLayoutClass {
    background: #fff;
    border: 1px solid #ddd;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column
}

.headPClass {
    line-height: 40px;
    height: 40px;
    box-sizing: border-box;
    border-bottom: 1px solid #ddd;
}

.bodyDivClass {
    flex: 1;
    position: relative;
    bottom: -2px;
    background-color: #fff;
    cursor: default;
}

.active {
    background-color: #5cb85c;
    /*background-color:#ec971f;*/
    cursor: default;
}

.main {
    background-color: #ec971f;
    cursor: default;
}

.toolTabs {
    height: 100%;
}

ul, li {
    list-style: none;
}

.bodyDivClass .itmelist {
    display: flex;
    align-items: center;
}

.itmelist p {
    flex: 1;
    margin: 0;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

.itmelist p:hover {
    color: #0000cc;
    cursor: pointer;
}

.bodyDivClass > ul {
    padding: 0 10px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 1px;
    overflow: auto;
}

.itmelist {
    padding-left: 20px;
    position: relative;
    line-height: 30px;
}

.itmelist:before {
    content: "■";
    display: inline-block;
    position: absolute;
    left: 0px;
    top: 50%;
    margin-top: -2px;
    font-size: 8px;
    width: 8px;
    height: 8px;
    line-height: 8px;
    color: #ccc;
}

.itmelist b {
    font-style: normal;
    display: inline-block;
    padding: 4px 8px;

}
.FormCustomEditControl{
    height: 100%;
    width: 100%;
    position: relative;
}
.FormCustomEditControl-prohibit{
    position: absolute;
    top: 0px;
    left: 0px;
    right: 20px;
    bottom: 20px;
    z-index: 9;
}
</style>